package in.sv.enge.service;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;

public class LocationAlertService extends Service {

	private String destination;

	private String message;

	private LocationManager mLocationManager;

	@Override
	public IBinder onBind(Intent arg0) {
		Toast.makeText(this, "LocationAlertService.onBind()", Toast.LENGTH_LONG)
				.show();
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Toast.makeText(this, "LocationAlertService.onCreate()",
				Toast.LENGTH_LONG).show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Toast.makeText(this, "LocationAlertService.onDestroy()",
				Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Toast.makeText(this, "LocationAlertService.onUnBind()",
				Toast.LENGTH_LONG).show();
		return super.onUnbind(intent);
	}

	@Override
	public void onStart(Intent intent, int startId) {

		super.onStart(intent, startId);

		Bundle bundle = intent.getExtras();
		destination = (String) bundle.getCharSequence("destination");
		message = (String) bundle.getCharSequence("message");

		Toast.makeText(this, "LocationAlertService.onStart()",
				Toast.LENGTH_LONG).show();
		Toast.makeText(
				this,
				"LocationAlertService.onStart() with \n" + "destination = "
						+ destination + "\n" + "message = " + message,
				Toast.LENGTH_LONG).show();

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String locationprovider = mLocationManager.getBestProvider(criteria,
				true);
		Location mLocation = mLocationManager
				.getLastKnownLocation(locationprovider);
		List<Address> addresses;

		Geocoder mGC = new Geocoder(this, Locale.ENGLISH);
		StringBuilder mSB = new StringBuilder("Address:\n");
		try {
			addresses = mGC.getFromLocation(mLocation.getLatitude(),
					mLocation.getLongitude(), 1);
			if (addresses != null) {
				Address currentAddr = addresses.get(0);

				for (int i = 0; i < currentAddr.getMaxAddressLineIndex(); i++) {
					mSB.append(currentAddr.getAddressLine(i)).append("\n");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendTextMessage(destination, null, mSB.toString(), null,
				null);

	}

}
